import React from 'react';
import {Animated, Easing, Platform, StyleSheet, View} from 'react-native';
import Toast from 'react-native-easy-toast';

import api from '../../../common/api';

import Sort from '../sort';
import Header from '../../../components/header';
import List from '../../../components/list';
import Loading from '../../../components/loading';

export default class extends React.Component {
    state = {
        isInit: false,
        title: '',
        cate_id: 0,          //商品分类ID， 0表示获取全部分类
        seller_id: 0,         //卖家ID，0 表示获取全部商家
        volume_sort: 0,          //销量排序，1升序 2降序
        coupon_sort: 0,          //优惠券价值排序，1升序 2降序
        share_price_sort: 0,      //分享价排序，1升序 2降序
        price_sort: 0,           //券后价格排序，1升序 2降序
        is_9kuai9: 0,                //是否9块9包邮 0 否 1是
        isShowDownList: false,     //是否显示下拉筛选
        list: [],
        page: 1,
        page_size: 20,
        isFetching: false,
        refreshing: false,
        hasMore: true,
        needRest: false,
        coverOpacity: new Animated.Value(0),
        downListTop: new Animated.Value(-172),
        myList: null
    };

    //获取数据
    getData = isRefresh => {
        let {isFetching, refreshing, page, page_size, list, hasMore, needRest, cate_id, seller_id, volume_sort, coupon_sort, share_price_sort, price_sort, is_9kuai9, myList} = this.state;
        page = isRefresh ? 1 : page;
        if (isFetching || !hasMore || refreshing) {
            return;
        }
        if (isRefresh) {
            this.setState({
                refreshing: true
            });
        } else {
            this.setState({
                isFetching: true
            });
        }

        let data = {
            page,
            page_size
        };
        if (cate_id) {
            data.cate_id = cate_id;
        }
        if (seller_id) {
            data.seller_id = seller_id;
        }
        if (volume_sort) {
            data.volume_sort = volume_sort;
        }
        if (coupon_sort) {
            data.coupon_sort = coupon_sort;
        }
        if (share_price_sort) {
            data.share_price_sort = share_price_sort;
        }
        if (price_sort) {
            data.price_sort = price_sort;
        }
        if (is_9kuai9) {
            data.is_9kuai9 = is_9kuai9;
        }
        api({
            url: 'api/item/getItemListByPage',
            data
        })
            .then(data => {
                this.setState({
                    list: isRefresh || needRest ? data : [...list, ...data],
                    page: page + 1,
                    hasMore: data.length >= page_size
                });
                if (needRest) {
                    setTimeout(() => {
                        myList && myList.scrollToIndex({
                            index: 0
                        });
                    }, 0);
                }
            })
            .catch(e => {
                console.error(e);
                this.showToast(e.msg);
            })
            .finally(() => {
                this.setState({
                    isFetching: false,
                    refreshing: false,
                    needRest: false
                });
            });
    };

    //设置排序条件
    setSort = (state = {}) => {
        const {isFetching, refreshing, volume_sort, coupon_sort, share_price_sort, price_sort, is_9kuai9, isShowDownList} = this.state;
        if (isFetching || refreshing) {
            return;
        }
        let entries;
        for (let [key, value] of Object.entries(state)) {
            entries = [key, value];
        }
        let newState = {},
            needFetch = true;
        if (entries[0] === 'all') {
            if (entries[1] === 1) {
                if (volume_sort > 0 || share_price_sort > 0 || price_sort > 0) {
                    state = {volume_sort: 0, share_price_sort: 0, price_sort: 0};
                } else {
                    needFetch = false;
                    state = {isShowDownList: !isShowDownList, coupon_sort, is_9kuai9};
                    this.transAni();
                }
            }
        }
        let params = {
            volume_sort: 0,
            coupon_sort: 0,
            share_price_sort: 0,
            price_sort: 0,
            is_9kuai9: 0,
            isShowDownList: false,
            page: 1,
            hasMore: true,
            needRest: true
        };
        newState = {...params, ...state};
        if (newState.isShowDownList === false) {
            newState.coverOpacity = new Animated.Value(0);
            newState.downListTop = new Animated.Value(-172);
        }
        this.setState(prevState => ({
            ...prevState, ...newState
        }), () => {
            if (needFetch) {
                this.getData();
            }
        });
    };

    transAni = () => {
        Animated.timing(                            // 随时间变化而执行的动画类型
            this.state.coverOpacity,                      // 动画中的变量值
            {
                duration: 250,
                toValue: 1,                             // 透明度最终变为1，即完全不透明
            }
        ).start();
        Animated.timing(                            // 随时间变化而执行的动画类型
            this.state.downListTop,                      // 动画中的变量值
            {
                easing: Easing.linear,
                duration: 250,
                toValue: 40,                             // 透明度最终变为1，即完全不透明
            }
        ).start();
    };

    setCurrentList = (list) => {
        this.setState({
            myList: list
        });
    };

    //toast弹出
    showToast = (text, time = 1000) => {
        this.refs.toast.show(text, time);
    };

    componentDidMount() {
        const {params = {}} = this.props.navigation.state;
        this.setState({
            isInit: true,
            title: params.title || '',
            cate_id: params.cate_id || 0
        }, () => {
            this.getData();
        });

        this._didFocusSubscription = this.props.navigation.addListener(
            'didFocus',
            () => {
                const {isInit, list} = this.state;
                if (isInit && list.length === 0) {
                    this.getData();
                }
            }
        );
    }

    componentWillUnmount() {
        this._didFocusSubscription && this._didFocusSubscription.remove();
    }

    render() {
        const {title, list, hasMore, isFetching, needRest, volume_sort, coupon_sort, share_price_sort, price_sort, is_9kuai9, isShowDownList, refreshing, coverOpacity, downListTop} = this.state;
        return (
            <View style={styles.container}>
                <Header title={title}/>
                <Sort setSort={this.setSort}
                      volume_sort={volume_sort}
                      coupon_sort={coupon_sort}
                      share_price_sort={share_price_sort}
                      price_sort={price_sort}
                      is_9kuai9={is_9kuai9}
                      isShowDownList={isShowDownList}
                      coverOpacity={coverOpacity}
                      downListTop={downListTop}
                />
                <List
                    moreListStyle={styles.listStyle}
                    list={list}
                    setCurrentList={this.setCurrentList}
                    isFetching={isFetching}
                    hasMore={hasMore}
                    refreshing={refreshing}
                    endReachedFn={() => {
                        this.getData(false);
                    }}
                    refreshFn={() => {
                        this.getData(true);
                    }}
                    ListHeaderComponent={this.headerComponent}
                    onScroll={this.onScroll}
                />
                <Loading isLoading={needRest && isFetching || list.length === 0 && isFetching}/>
                <Toast ref="toast" position="center"/>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        backgroundColor: '#f6f6f5',
        flex: 1
    },
    listStyle: {
        ...Platform.select({
            ios: {
                marginTop: 62
            },
            android: {
                marginTop: 42
            },
        }),
    }
});
